<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="语言" prop="langueType">
        <el-select v-model="queryParams.langueType" placeholder="语言" clearable size="small" @change="langueTypeChange">
          <el-option
            v-for="dict in langueTypeOptions"
            :key="dict.id"
            :label="dict.name"
            :value="dict.val"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="类型" prop="type">
        <el-select v-model="queryParams.type" placeholder="新闻类型" clearable size="small">
          <el-option
            v-for="dict in typeLangueOptions"
            :key="dict.id"
            :label="dict.name"
            :value="dict.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="发布人" prop="nameUser">
        <el-input
          v-model="queryParams.nameUser"
          placeholder="请输入发布人"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="新闻标题" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入新闻标题"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['/journalism/insert']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['/journalism/updateById']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['/journalism/deleteById']"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="journalismList" @selection-change="handleSelectionChange" :border="true">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" prop="id" width="100" />
      <el-table-column label="新闻标题" align="center" prop="title" :show-overflow-tooltip="true" />
      <el-table-column label="简介" align="center" prop="synopsis" :show-overflow-tooltip="true" />
      <el-table-column label="新闻类型" align="center" prop="type" :formatter="typeFormat" width="100" />
      <el-table-column label="发布人" align="center" prop="nameUser" />
      <el-table-column label="状态" align="center" prop="status" :formatter="statusFormat" width="100" />
      <el-table-column label="创建时间" align="center" prop="createAt" width="100">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createAt, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['/journalism/updateById']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['/journalism/deleteById']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改新闻对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="780px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="新闻类型" prop="type">
              <el-select v-model="langueTypeUpdate" placeholder="语言" clearable size="small" @change="langueTypeUpdateChange">
                <el-option
                  v-for="dict in langueTypeOptions"
                  :key="dict.id"
                  :label="dict.name"
                  :value="dict.val"
                />
              </el-select>
              <el-select v-model="form.type" placeholder="请选择">
                <el-option
                  v-for="dict in typeLangueUpdateOptions"
                  :key="dict.id"
                  :label="dict.name"
                  :value="dict.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="新闻标题" prop="title">
              <el-input v-model="form.title" placeholder="请输入新闻标题" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="新闻简介" prop="synopsis">
              <el-input v-model="form.synopsis" placeholder="请输入新闻标题" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="图片" prop="img">
              <uploadImage v-model="form.img"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="内容" prop="content">
              <editor v-model="form.content" :min-height="192"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="状态">
              <el-radio-group v-model="form.status">
                <el-radio
                  v-for="dict in statusOptions"
                  :key="dict.val"
                  :label="dict.val"
                >{{dict.name}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listJournalism, getJournalism, delJournalism, addJournalism, updateJournalism } from "@/api/journalism/info";
import { listJournalismType } from "@/api/journalism/type";
import UploadImage from '@/components/UploadImage';
import Editor from '@/components/Editor';
import { LANGUE_TYPE, PAGE_SIZE } from "@/constant/constant";
import { GENERAL_STATUS } from "@/enum/enum";

export default {
  name: "Journalism",
  components: {
    UploadImage,
    Editor
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 新闻表格数据
      journalismList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 状态数据字典
      statusOptions: [],
      // 类型数据字典
      typeOptions: [],
      // 类型数据字典
      typeLangueOptions: [],
      // 语言类型数据字典
      langueTypeOptions: [],
      // 类型数据字典
      typeLangueUpdateOptions: [],
      // 添加修改时候的语言类型
      langueTypeUpdate: undefined,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: PAGE_SIZE,
        langueType: LANGUE_TYPE,
        type: undefined,
        nameUser: undefined,
        title: undefined,
        createBy: undefined,
        status: undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        title: [
          { required: true, message: "新闻标题不能为空", trigger: "blur" }
        ],
        synopsis: [
          { required: true, message: "新闻简介不能为空", trigger: "blur" }
        ],
        content: [
          { required: true, message: "新闻内容不能为空", trigger: "blur" }
        ],
        img: [
          { required: true, message: "新闻图片不能为空", trigger: "blur" }
        ],
        type: [
          { required: true, message: "新闻类型不能为空", trigger: "change" }
        ]
      }
    };
  },
  created() {
    this.getList();
    this.getDicts("general_status").then(response => {
      response.data.forEach(element => {
        element.val = parseInt(element.val)
      });
      this.statusOptions = response.data;
    });
    this.getDicts("langue_type").then(response => {
      response.data.forEach(element => {
        element.val = parseInt(element.val)
      });
      this.langueTypeOptions = response.data;
    });
    listJournalismType().then(response => {
      this.typeOptions = response.data;
      this.langueTypeChange();
    });
  },
  methods: {
    /** 查询新闻列表 */
    getList() {
      this.loading = true;
      listJournalism(this.queryParams).then(response => {
        this.journalismList = response.data;
        this.total = response.page.total;
        this.loading = false;
      });
    },
    // 新闻状态字典翻译
    statusFormat(row, column) {
      return this.selectDictLabel(this.statusOptions, row.status);
    },
    // 新闻类型字典翻译
    typeFormat(row, column) {
      var actions = [];
      Object.keys(this.typeOptions).some((key) => {
        if (this.typeOptions[key].id == row.type) {
          actions.push(this.typeOptions[key].name);
        }
      })
      return actions.join('');
    },
    // 语言改变的时候触发
    langueTypeChange() {
      if(this.queryParams.langueType){
        this.typeLangueOptions = [];
        this.typeOptions.forEach(element => {
          if(element.langueType == this.queryParams.langueType){
            this.typeLangueOptions.push(element);
          }
        });
      }else{
        this.typeLangueOptions = this.typeOptions;
      }
      if(this.queryParams.type){
        if(this.typeLangueOptions.length > 0){
          this.queryParams.type = this.typeLangueOptions[0].id
        }else{
          this.queryParams.type = undefined
        }
      }
    },
    // 语言改变的时候触发
    langueTypeUpdateChange() {
      if(this.langueTypeUpdate){
        this.typeLangueUpdateOptions = [];
        this.typeOptions.forEach(element => {
          if(element.langueType == this.langueTypeUpdate){
            this.typeLangueUpdateOptions.push(element);
          }
        });
      }else{
        this.typeLangueUpdateOptions = this.typeOptions;
      }
      if(this.form.type){
        if(this.typeLangueUpdateOptions.length > 0){
          this.form.type = this.typeLangueUpdateOptions[0].id
        }else{
          this.form.type = undefined
        }
      }
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        title: undefined,
        content: undefined,
        img: undefined,
        type: this.queryParams.type,
        status: GENERAL_STATUS.NORMAL.code,
      };
      this.langueTypeUpdate = this.queryParams.langueType;
      this.typeLangueUpdateOptions = this.typeLangueOptions;
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
      this.langueTypeChange();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!=1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加新闻";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getJournalism(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改新闻";
      });
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != undefined) {
            updateJournalism(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addJournalism(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$confirm('是否确认删除新闻编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delJournalism(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(() => {});
    }
  }
};
</script>